package spring.cloud.simple.hello.controller;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.GetMapping;

@RestController
public class HelloController {
    private static volatile int n = 0;
    private Executor executor = Executors.newFixedThreadPool(10);

    @Value("${hello}")
    private String hello;

    @GetMapping("/hello.html")
    public String hello() {
        System.out.println("Current thread: " + Thread.currentThread().getName());
        System.out.println("Handling task:" + (++n));
        System.out.println("Finished task: " + n);
        return hello + " " + n;
    }

    @GetMapping("/hello/{path}.html")
    public String hello(@PathVariable("path") final String path) {
        Runnable runnable = new RunnableImpl(path);
        executor.execute(runnable);
        return "Hello - " + path;
    }

    private class RunnableImpl implements Runnable {
        private String path;

        public RunnableImpl(String path) {
            this.path = path;
        }

        @Override
        public void run() {
            System.out.println("Current thread - " + Thread.currentThread().getName());
            System.out.println("Handling task - " + path);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Finished task - " + path);
        }
    }
}
